#include "calibrate.h"
#include "ui_calibrate.h"
#include "stdio.h"
#include "myThread.h"

Calibrate::Calibrate(QWidget *parent) : QDialog(parent), calui(new Ui::Calibrate)
{
    calui->setupUi(this);
    progress = 0;


    thread1 = new MyThread1(this);
    thread2 = new MyThread(this);
    thread3 = new MyThread(this);
    thread4 = new MyThread(this);


    QObject::connect( &*thread1, SIGNAL( MySignal() ), this, SLOT( updateProgress() ) );

    connect(&timer, SIGNAL(timeout()), this, SLOT(timedOut()));
    timer.start(50);
}

void Calibrate::updateProgress()
{
    progress++;
    calui->Progress->setValue(progress);
}

// starts a big for loop thread for half your cores
void Calibrate::on_WorkingButton_clicked()
{
    calui->StressedButton->setDisabled(true);

    int coreNum1;

    coreNum1 = getCores();

    calui->lcdNumber->display(coreNum1);

    switch(coreNum1)
    {
        case 1:

        case 2:

        thread1->start(QThread::TimeCriticalPriority);
        break;
        case 3:

        case 4:

        thread1->start(QThread::TimeCriticalPriority);

        thread2->start(QThread::TimeCriticalPriority);
        break;


    }

}

// starts a big for loop thread for each core
void Calibrate::on_StressedButton_clicked()
{
    calui->WorkingButton->setDisabled(true);

    int coreNum2;

    coreNum2 = getCores();

    calui->lcdNumber->display(coreNum2);

    switch(coreNum2)
    {
        case 1:

        thread1->start(QThread::TimeCriticalPriority);
        break;
        case 2:

        thread1->start(QThread::TimeCriticalPriority);

        thread2->start(QThread::TimeCriticalPriority);

        break;
        case 3:

        thread1->start(QThread::TimeCriticalPriority);

        thread2->start(QThread::TimeCriticalPriority);

        thread3->start(QThread::TimeCriticalPriority);
        break;
        case 4:

        thread1->start(QThread::TimeCriticalPriority);

        thread2->start(QThread::TimeCriticalPriority);

        thread3->start(QThread::TimeCriticalPriority);

        thread4->start(QThread::TimeCriticalPriority);
        break;


    }

}

//returns the number of cores you have
// must have #include "stdio.h"
int Calibrate::getCores()
{
    char buf[1];
    int cores;

    FILE *fp = popen("grep -c \"^processor\" /proc/cpuinfo", "r");

    buf[0] = (char)fgetc( fp);

    cores = atoi(buf);

    fclose(fp);

    return cores;

}




//Enables / disable buttons when you click radio buttons
void Calibrate::timedOut()
{
    int temp;
    temp = getCores();
    if(calui->radioButton->isChecked()) // auto mode
    {
        calui->WorkingButton->setDisabled(true);
        calui->StressedButton->setDisabled(true);

        mySys.cores = temp;
    }
    else if(calui->radioButton_2->isChecked()) // calibration mode
    {
        calui->WorkingButton->setDisabled(false);
        calui->StressedButton->setDisabled(false);
    }
}

